package com.xs.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongTest {

	public static void main(String[] args) {

		MongoClient mongoClient = new MongoClient("localhost", 27017);

		MongoDatabase database = mongoClient.getDatabase("users");

		MongoCollection<Document> goodUsersCollection = database.getCollection("goodUsers");

		MongoCollection<Document> badCollection = database.getCollection("badUsers");

		/*
		 * for (int i=0 ; i < 20;i++) { Document document = new Document();
		 * document.append("userName", "zhangsna" + i) .append("age", 18 + i)
		 * .append("add", "xi'an"); goodUsersCollection.insertOne(document); }
		 */
		// goodUsersCollection.deleteMany(Filters.eq("userName", "zhangsna1"));

		FindIterable<Document> find = goodUsersCollection.find(Filters.eq("userName", "zhangsna2"));

		FindIterable<Document> findAll = goodUsersCollection.find().sort(new Document().append("age", 1))
				.filter(Filters.gt("age", 30));

		Document updateData = new Document();
		updateData.append("age", 100);

		Document update = new Document();
		update.append("$set", updateData);

		// Document findOneAndUpdate =
		// goodUsersCollection.findOneAndUpdate(Filters.eq("userName", "zhangsna2"),
		// update);

		// System.out.println(findOneAndUpdate);

		MongoCursor<Document> iterator = findAll.iterator();

		while (iterator.hasNext()) {
			Document next = iterator.next();
			System.out.println(next);
		}

		mongoClient.close();

	}

}
